/*
 * PageList.java 1.0 Created on 2003. 2. 24.
 */

package com.zll.framework.util;

import java.text.*;
import java.util.*;
import java.io.*;
import java.util.regex.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

import com.zll.framework.model.HashList;

public class StringUtil {

	public static int LINE_PER_PAGE	= 15;

	public static int PAGE_MOVE = 10;

	public static String home = "";


	public static String nvl(Object str)
	{
		if ("____.__.__".equals(str)) {
			str = "";
		}

		if (str == null) {
			return "";
		}
		else if (str instanceof java.lang.Integer) {
			return str.toString();
		}
		else {
			return (String)str;
		}
	}

	public static String nvl(Object str, String replace)
	{
		if ("____.__.__".equals(str)) {
			str = "";
		}

		if (str == null || str.equals("")) {
			return replace;
		}
		else {
			return (String)str;
		}
	}

	public static boolean isAlphaNumber(String str)
	{
		for (int i = 0; i < str.length(); i++)
		{
			char value = str.toUpperCase().charAt(i);

			if (value < 48 || value > 90 || ( value > 57 && value < 65))
			{
				return false;
			}
		}
		return true;
	}

	/**
	* 8859_1 에서 EUC-KR 로 인코딩 한다.
	* @param str 원본 String
	* @return String 변환된 내용
	*/
	public static String toHan(Object str){
		if (str == null)	return "";
		String rstr = "";
		try{
		  rstr=(str==null)?"":new String(((String)str).getBytes("8859_1"),"utf-8");
		} catch(java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return rstr;
	}

	/**
	* 8859_1 에서 EUC-KR 로 인코딩 한다.
	* @param str 원본 String
	* @return String 변환된 내용
	*/
	public static String toEng(String str){
		if (str == null)	return null;
		String rstr=null;
		try{
		  rstr=(str==null)?"":new String(str.getBytes("euc-kr"),"8859_1");
		} catch(java.io.UnsupportedEncodingException e) {
		}
		return rstr;
	}

	/**
	* 8859_1 에서 EUC-KR 로 인코딩 한다.
	* @param str 원본 String
	* @return String 변환된 내용
	*/
	public static String decode(String str, String enc){
		if (str == null)	return "";
		String rstr = "";
		try{
			rstr = java.net.URLDecoder.decode(str, enc);
		} catch (java.io.UnsupportedEncodingException e) {
		}
		return rstr;
	}

	/**
	* 금액에 천단위 콤마를 찍는다.
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String toPrice(long sumPrice)
	{
		DecimalFormat df = new DecimalFormat("###,###,###");

		return df.format(sumPrice);
	}


	/**
	* 금액에 천단위 콤마를 찍는다.
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String toPrice(String sumPrice)
	{
		if (sumPrice == null || sumPrice.trim().equals("")) {
			return "";
		}

		DecimalFormat df = new DecimalFormat("###,###,###");

		return df.format(Long.parseLong(sumPrice));
	}

	/**
	* 금액에 천단위 콤마를 찍는다.
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String toEngPrice(String sumPrice)
	{
		if (sumPrice == null || sumPrice.trim().equals("")) {
			return "";
		}

		DecimalFormat df = new DecimalFormat("###,###,###.##");

		return df.format(Double.parseDouble(sumPrice));
	}

	/**
	* 날자형식을 반환
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String toDate(String aDate, String delimeter)
	{
		if (aDate == null) {
			return "";
		} else if (aDate.length() == 8) {
			return aDate.substring(0,4) + delimeter + aDate.substring(4,6) + delimeter + aDate.substring(6);
		} else if (aDate.length() == 6) {
			return aDate.substring(0,4) + delimeter + aDate.substring(4);
		} else if (aDate.length() == 4) {
			return aDate.substring(0,2) + delimeter + aDate.substring(2);
		} else {
			return aDate;
		}
	}

	/**
	* 날자형식을 반환
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String toDate(String aDate)
	{
		return toDate(aDate, "-");
	}

	/**
    * 날자형식을 반환
    * @param        원본 숫자
    * @return       콤마 찍은 숫자.
    */
	public static String toSimpleDate(String str, String filler)
	{
		if (str.length() == 8) {
			return str.substring(2,4) + filler + str.substring(4,6) + filler + str.substring(6);
		} else if (str.length() == 6) {
			return str.substring(2,4) + filler + str.substring(4);
		} else {
			return str;
		}
	}

	/**
    * 날자형식을 반환
    * @param        원본 숫자
    * @return       콤마 찍은 숫자.
    */
	public static String toSDate(String str)
	{
		if (str.length() == 8) {
			return str.substring(4,6) + "/" + str.substring(6);
		} else {
			return str;
		}
	}


    /**
    * 날자형식을 반환
    * @param        원본 숫자
    * @return       콤마 찍은 숫자.
    */
    public static String toEngDate(String str, String filler, boolean bool)
    {
		int pos = 0;

		if (bool) pos = 2;

        if (str.length() == 8) {
                return str.substring(4,6) + filler + str.substring(6) + filler + str.substring(pos,4);
        } else if (str.length() == 6) {
                return str.substring(4) + filler + str.substring(pos,4);
        } else {
                return str;
        }
    }

	/**
	* 날자형식을 반환
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String fromDate(String aDate)
	{
		if (aDate == null) {
			return "";
		} else {
			return aDate.replaceAll("-", "");
		}
	}

	/**
	* 날자형식을 반환
	* @param	원본 숫자
	* @return	콤마 찍은 숫자.
	*/
	public static String toOX(String sYN)
	{
		if ("Y".equals(sYN)) {
			return "O";
		} else if ("N".equals(sYN)) {
			return "X";
		} else {
			return sYN;
		}
	}

	public static int parseInt(String str)
	{
		if (str == null || str.equals("")) {
			return 0;
		} else {
			try {
				return Integer.parseInt(str);
			} catch (Exception e) {
				return 0;
			}
		}
	}



	public static String checked(Object str, Object str2)
	{
		if (str == null || str2 == null)	return "";

		if (str.equals(str2))				return "checked=\"checked\"";
		else								return "";
	}

	public static String selected(Object str, Object str2)
	{
		if (str == null || str2 == null)	return "";

		if (str.equals(str2))				return "selected=\"selected\"";
		else								return "";
	}

	public static String toHTML(String org)
	{
		if (org == null)	return "";
		return org.replaceAll("\n", "<br/>");
	}

	public static String toTag(String org)
	{
		if (org == null) 	return org;
		org = org.replaceAll("'", "&apos;");

		return org;
	}

	public static String noBR(String org)
	{
//		return org.replaceAll("\n", "<BR>");

		if (org == null)	return org;

		StringBuffer temp = new StringBuffer();

		int pos = -1;
		for (int i = 0; i < org.length(); i++)
		{
			if (org.charAt(i) == 13)
			{
				temp.append(org.substring(pos+1, i));
				pos = i+1;
			}
		}

		temp.append(org.substring(pos+1));

		return temp.toString();
	}

	public static String toReply(String org)
	{
//		return org.replaceAll("\n", "<BR>");

		if (org == null)	return org;

		StringBuffer temp = new StringBuffer();

		int pos = -1;
		for (int i = 0; i < org.length(); i++)
		{
			if (org.charAt(i) == 13)
			{
				temp.append(">" + org.substring(pos+1, i));
				pos = i+1;
			}
		}

		temp.append(">" + org.substring(pos+1));

		return temp.toString();
	}


	public static String substring(String org, int lastIndex)
	{
		return substring(org, 0, lastIndex, "..");
	}


	public static String substring(String org, int lastIndex, String tail)
	{
		return substring(org, 0, lastIndex, tail);
	}


	public static String substring(String org, int startIndex, int lastIndex)
	{
		return substring(org, startIndex, lastIndex, "");
	}

	public static String substring(String org, int startIndex, int lastIndex, String tail)
	{
		if (org == null || org.equals(""))	return "";

		if (org.length() <= lastIndex)
		{
			return org;
		}

		return org.substring(startIndex, lastIndex) + tail;
	}

	// fromIndex로 부터 뒤로 str을 찾는다.
	public static int firstIndexOf(String org, String str, int fromIndex)
	{
		int index = -1;

		for (int i = fromIndex; i > -1; i--)
		{
			if (org.charAt(i) == str.charAt(0))
			{
				boolean isSame = true;

				// 나머지부분이 일치하는 지 확인
				for (int j = 1; j < str.length(); j++)
				{
					if (org.charAt(i+j) != str.charAt(j))
					{
						isSame = false;
					}
				}

				if (isSame)
				{
					index = i;
					break;
				}
			}
		}

		return index;
	}


	public static String getCurrentDate()
	{
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy년 M월 d일 a h시 m분");
		String strDate = df.format(cal.getTime());

		return strDate;
	}

	public static String today() {
		return toString(Calendar.getInstance());
	}

	/**
	 * today : YYYYMMDD
	 */
	public static String addDays(String yyyymmdd, int days) {
		GregorianCalendar cal = toCalendar(yyyymmdd);
		cal.add(GregorianCalendar.DATE, days);
		return toString(cal);
	}

	public static String toString(Calendar cal) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		return df.format(cal.getTime());
	}

	public static GregorianCalendar toCalendar(String yyyymmdd) {
		int yyyy 	= Integer.parseInt(yyyymmdd.substring(0,4));
		int mm		= Integer.parseInt(yyyymmdd.substring(4,6));
		int dd		= Integer.parseInt(yyyymmdd.substring(6));

		return new GregorianCalendar(yyyy, mm-1, dd,0,0,0);
	}

	public static String noData(int cnt)
	{
		if (cnt == 0) {
			return "<tr height=50 class=pad_l10><td align=center>검색된 데이타가 없습니다.</td></tr>";
		} else {
			return "";
		}
	}



	public static String noHTML(String html)
	{
	    Pattern p = Pattern.compile("\\<(\\/?)(\\w+)*([^<>]*)>");
	    Matcher m = p.matcher(html);
	    return m.replaceAll("");
	}


	/**
  * replaces the pattern string in the source string with replace string
  * @author  Lee Hyun Sung in Love & Thanks
  * @param strSource  the string to be processed
  * @param strPat     the string pattern to be replaced
  * @param strReplace the replace string
  * @return  the newly formed replaced string else empty string
  */
	public static String  replaceAll(String strSource, String strPat, String strReplace)
	{
		int sPos = strSource.indexOf(strPat);
		StringBuffer newSource = new StringBuffer();

		while (sPos > -1)
		{
			strSource = strSource.substring(0, sPos) + strReplace + strSource.substring(sPos + strPat.length());
			sPos = strSource.indexOf(strPat);
		}

		return strSource;
	}


	/**
  * replaces the pattern string in the source string with replace string
  * @author  Lee Hyun Sung in Love & Thanks
  * @param strSource  the string to be processed
  * @param strPat     the string pattern to be replaced
  * @param strReplace the replace string
  * @return  the newly formed replaced string else empty string
  */
	public static String  replaceFirst(String strSource, String strPat, String strReplace)
	{
		int sPos = strSource.indexOf(strPat);
		StringBuffer newSource = new StringBuffer();

		if (sPos > -1)
		{
			strSource = strSource.substring(0, sPos) + strReplace + strSource.substring(sPos + strPat.length());
			sPos = strSource.indexOf(strPat);
		}

		return strSource;
	}


    public static String getPageMove(int aTotalPage, int aCurrentPage )
    {
        StringBuffer result = new StringBuffer(100);
        if(aTotalPage == 0)
        {
            aTotalPage = 1;
        }
        if(aCurrentPage == 0)
        {
            aCurrentPage = 1;
        }
        if(aCurrentPage > aTotalPage)
        {
            aCurrentPage = aTotalPage;
        }

        int iTotalPos = (int)((aTotalPage - 1) / PAGE_MOVE) + 1;   //마지막 페이지가 존재하는 위치
        int iCurrentPos = (int)((aCurrentPage - 1) / PAGE_MOVE) + 1;   //현재 페이지가 존재하는 위치

        //화면에 나타나는 페이지 갯수
        int iViewPageCount = 1;
        if(iCurrentPos == iTotalPos)
        {
            iViewPageCount = aTotalPage % PAGE_MOVE == 0 ? PAGE_MOVE : aTotalPage % PAGE_MOVE;
        }
        else
        {
            iViewPageCount = PAGE_MOVE ;
        }

		result.append("<td align=\"center\" class=\"gray\">\n");

        ////////////////////////////////////////////////////////////////////////
        //이전 10페이지로 이동 버튼 설정
        if(iCurrentPos > 1)
        {
            int iRewPage = (iCurrentPos - 2) * PAGE_MOVE + 1;
            result.append("<a href=\"javascript:goList('").append(iRewPage).append("');\" onfocus=\"this.blur()\" ><IMG name=\"ImgPageRew\"  border=\"0\" src=\"/img/icon/ico_prev.jpg\"  align=\"absmiddle\" alt=\"10 페이지 이전으로 이동\"></a><span class=\"PageSplitHBetBtn\"></span>&nbsp;&nbsp;");
        }
        else
        {
//            result.append("<IMG border=\"0\" src=\"/images/pre_i.jpg\"   align=\"absmiddle\" alt=\"10 페이지 이전으로 이동\"><SPAN class=\"PageSplitHBetBtn\"></SPAN>");
        }
        ////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////
        //이전 페이지 버튼 설정
        int iBackPage = aCurrentPage - 1;

        if(iBackPage >= 1)
        {
//            result.append("<A href=\"javascript:goList('").append(iBackPage).append("');\"  onfocus=\"this.blur()\" onMouseOut=\"document.images['ImgPagePrev'].src='/images/page_prev_1.gif' \" onMouseOver=\"document.images['ImgPagePrev'].src='/images/page_prev_2.gif' \"><IMG name=\"ImgPagePrev\" border=\"0\" src=\"/images/page_prev_1.gif\"  align=\"absmiddle\" alt=\"이전 페이지로 이동\"></A><SPAN class=\"PageSplitHBetBtnNo\"></SPAN>");
        }
        else
        {
//            result.append("<IMG  border=\"0\" src=\"/img/icon/pre_i.gif\"  align=\"absmiddle\" alt=\"이전 페이지로 이동\"><SPAN class=\"PageSplitHBetBtnNo\"></SPAN>");
        }
        ////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////
        //페이지 숫자 표시
        for(int i = 1 ; i <= iViewPageCount && (iCurrentPos - 1) * PAGE_MOVE + i <= aTotalPage; i++)
        {
            //현재 페이지인 경우 Link 없음
            if((iCurrentPos - 1) * PAGE_MOVE + i == aCurrentPage)
            {
//                result.append("<SPAN class=\"CurrPageNo\">[").append((iCurrentPos - 1) * PAGE_MOVE + i).append("]</SPAN>");
				result.append("<span class=\"currPageNo\">").append((iCurrentPos - 1) * PAGE_MOVE + i).append("</span>");
            }
            else
            {
//                result.append("<A href=\"javascript:goList('").append((iCurrentPos - 1)* PAGE_MOVE + i).append("')\"");
//                result.append(" class=\"PageNo\" onfocus=\"this.blur()\">[").append((iCurrentPos - 1) * PAGE_MOVE + i).append("]</A>");
				result.append("<a href=\"javascript:goList('").append((iCurrentPos - 1)* PAGE_MOVE + i).append("')\"");
                result.append(" class=\"pageNo\" onfocus=\"this.blur()\">").append((iCurrentPos - 1) * PAGE_MOVE + i).append("</a>");

            }
        }//end of for loop
        ////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////
        //다음 페이지 버튼 설정
        int iNextPage = aCurrentPage + 1;
        if(iNextPage <= aTotalPage)
        {
//            result.append("<span class=\"PageSplitHBetBtnNo\"></span>");
//            result.append("<A href=\"javascript:goList('").append(iNextPage).append("');\" onfocus=\"this.blur()\" onMouseOut=\"document.images['ImgPageNext'].src='/images/page_next_1.gif'\" onMouseOver=\"document.images['ImgPageNext'].src='/images/page_next_2.gif' \"><IMG name=\"ImgPageNext\" border=\"0\" src=\"/images/page_next_1.gif\"  align=\"absmiddle\" alt=\"다음 페이지로 이동\"></A><SPAN class=\"PageSplitHBetBtn\"></SPAN>");
        }
        else
        {
//            result.append("<span class=\"PageSplitHBetBtnNo\"></span>");
//            result.append("<IMG border=\"0\" src=\"/images/page_next_0.gif\"  align=\"absmiddle\" alt=\"다음 페이지로 이동\"><SPAN class=\"PageSplitHBetBtn\"></SPAN>");
        }
        ////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////
        //다음 10페이지 이동 버튼 설정
        int iNextPos = iCurrentPos * PAGE_MOVE + 1;
        if(iNextPos <= aTotalPage)
        {
            result.append("&nbsp;&nbsp;<a href=\"javascript:goList('").append(iNextPos).append("');\"  onfocus=\"this.blur()\" ><img name=\"ImgPageFF\" border=\"0\" src=\"/img/icon/ico_next.jpg\"   align=\"absmiddle\" alt=\"10 페이지 다음으로 이동\"></a>\n");
        }
        else
        {
//            result.append("<IMG  border=\"0\" src=\"/img/icon/next_i.jpg\"  align=\"absmiddle\" alt=\"10 페이지 다음으로 이동\">\n");
        }
	    result.append("</td>\n");

        return result.toString();
    }


    /**
	* 해당파일을 copy하는 메소드
	* @param slc => 원본파일경로
	* @param tlc => 복사될파일경로
	* @throws IOException
	*/
	public static void copyFile(File slc , File tlc) throws IOException{
		//소스가 디렉토리인 경우
		//-->해당 디렉토리의 모든 파일을 타겟 디렉토리에 복사
		if(slc.isDirectory()){
			if(!tlc.exists()){
				tlc.mkdir();
			}

			String[] children = slc.list();
			for(int i=0; i<children.length; i++){
				copyFile(new File(slc,children[i]),new File(tlc,children[i]));
			}
		}

		//소스가 파일인경우
		else{
			InputStream in = new FileInputStream(slc);
			OutputStream out = new FileOutputStream(tlc);

			byte[] buf = new byte[1024];
			int len;
			while((len = in.read(buf)) > 0){
				out.write(buf,0,len);
			}
			in.close();
			out.close();
		}
	}


	public static String replaceContent(String content, String dir)  throws IOException
	{
		String realPath	= "/home/hosting_users/joinhawaii/www/";	//request.getRealPath("/");

		while (content.indexOf("img/temp/") > -1)
		{
			int idx = content.indexOf("img/temp/");
			String fileName = content.substring(idx+9, content.indexOf(".", idx)+4);

			content = StringUtil.replaceFirst(content, "img/temp", dir);


			File f = new File(realPath + "img/temp/" + fileName);

			StringUtil.copyFile(f, new File(realPath + dir+"/"+fileName));
			f.delete();
		}

		return content;
	}


	public static String latlng(String xml, String name, String latlng) {
		String value = "";
		try
		{

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   //XML을 다루는 CLASS
			DocumentBuilder parser = dbf.newDocumentBuilder();                   //XML을 다루는 CLASS
			Document doc  = parser.parse(new StringBufferInputStream(xml));

			Element root = doc.getDocumentElement();
			NodeList nodeList = root.getElementsByTagName(name);
			Node location = nodeList.item(0);


			NodeList locList = location.getChildNodes();
			for (int i = 0; i < locList.getLength(); i++) {
				Node node = locList.item(i);
				if (node.getNodeName() == latlng) {
					Node textNode = node.getChildNodes().item(0);
					value = textNode.getNodeValue();
					break;
				}
			}
		}
		catch (Exception e) {

		}

		return value;
	}


	public static String lpad(String str, int len, String addStr) {
        String result = str;
        int templen   = len - result.length();

        for (int i = 0; i < templen; i++){
              result = addStr + result;
        }

        return result;
    }

	public static String makeRadio(HashList list, String name, String selectedValue) {

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < list.size(); i++) {
			sb.append("<input type=\"radio\"  name=\""+name+"\" id=\""+name+i+"\" value=\""+list.get("code",i)+"\" ");
			if (list.get("code",i).equals(selectedValue)) {
				sb.append(" checked=\"checked\" ");
			}
			sb.append(" /><label class=\"pl2 mr10\" for=\""+name+i+"\">"+list.get("code_name",i)+"</label>");
		}

		return sb.toString();
	}


	public static String makeOption(HashList list, String selectedValue) {

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < list.size(); i++) {
			sb.append("<option value=\""+list.get("code",i)+"\" ");
			if (list.get("code",i).equals(selectedValue)) {
				sb.append(" selected=\"selected\" ");
			}
			sb.append(" >"+list.get("code_name",i)+"</option>");
		}

		return sb.toString();
	}


	public static String makeOptionByGroup(HashList list, String selectedValue) {

		StringBuffer sb = new StringBuffer();

		String optionGroup	 	= "";
		boolean optGroupOpen	= false;


		for (int i = 0; i < list.size(); i++) {
			if (optionGroup.equals("") || !optionGroup.equals(list.get("option_group",i))) {
				if (optGroupOpen) {
					sb.append("</optgroup>");
					optGroupOpen = false;
				}
				sb.append("<optgroup label=\""+list.get("option_group",i)+"\">");
				optGroupOpen = true;
			}

			sb.append("<option value=\""+list.get("code",i)+"\" ");
			if (selectedValue.equals(list.get("code",i))) {
				sb.append(" selected=\"selected\" ");
			}
			sb.append(" >"+list.get("code_name",i)+"</option>");


			optionGroup = StringUtil.nvl(list.get("option_group",i));
		}

		if (optGroupOpen) {
			sb.append("</optgroup>");
		}

		return sb.toString();
	}

}
